package com.project.personnel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.personnel.entity.*;
import com.project.personnel.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.format.CellFormatType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

//基本资料
@RestController
@RequestMapping("/employee/basic")
public class BasicController {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Resource
    private EmployeeService employeeService;
    @Resource
    private PoliticsstatusService politicsstatusService;
    @Resource
    private NationService nationService;
    @Resource
    private PositionService positionService;
    @Resource
    private JoblevelService joblevelService;
    @Resource
    private DepartmentService departmentService;

    //test
    @GetMapping("/getAllList")
    public List<Employee> getAll() {
        return employeeService.list();
    }

    //按名字搜索
    @GetMapping("/getByName")
    public List<Employee> getByName(@RequestParam(defaultValue = "1") Integer current, Integer size, String name) {
        Page<Employee> employeePage = new Page<>(current, size);//设置分页参数
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
        employeeQueryWrapper.like("name", name);//设置查询条件
        IPage<Employee> employeeIPage = employeeService.page(employeePage, employeeQueryWrapper);
        return employeeIPage.getRecords();
    }


    //填充政治面貌
    @GetMapping("/getPoliticsStatus")
    public List<Politicsstatus> getPoliticsStatus() {
        return politicsstatusService.list();
    }

    //填充民族
    @GetMapping("/getNation")
    public List<Nation> getNation() {
        return nationService.list();
    }

    //填充职位
    @GetMapping("/getPosition")
    public List<Position> getPosition() {
        return positionService.list();
    }

    //填充职称
    @GetMapping("/getJobLevel")
    public List<Joblevel> getJobLevel() {
        return joblevelService.list();
    }

    //填充所属部门
    @GetMapping("/getDepartment")
    public List<Department> getDepartment() {
        return departmentService.list();
    }

    //高级搜索
    @GetMapping("/getAdvanced")
    public List<Employee> getAdvanced(@RequestParam(defaultValue = "1") Integer current, Integer size, Employee employee, Date[] beginDates) {
        if (current != null && size != null) {
            current = (current - 1) * size;
        }
        return employeeService.getAdvanced(current, size, employee, beginDates);
    }

    //查询全部列表
    @GetMapping("/getAllPage")
    public List<Employee> getUserPage(@RequestParam(defaultValue = "1") Integer current, Integer size) {
        Page<Employee> employeePage = new Page<>(current, size);
        IPage<Employee> employeeIPage = employeeService.page(employeePage);
        return employeeIPage.getRecords();
    }

    //查询全部列表，连表查询
    @GetMapping("/getAllLink")
    public List<Employee> getAllLink() {
        return employeeService.getAllLink();
    }

    //添加员工
    @PostMapping("/add")
    public boolean add(@RequestBody Employee employee) {
        return employeeService.save(employee);
        //return employeeService.add(employee);
    }

    //添加多员工
    @PostMapping("/adds")
    public boolean adds(@RequestBody List<Employee> employeeList) {
        return employeeService.saveBatch(employeeList);
        //return employeeService.addMultitude(employeeList);
    }

    //查询编辑员工
    @GetMapping("/getById")
    public Employee getById(@RequestParam("id") Integer id) {
        return employeeService.getById(id);
        //return employeeService.getEmployeeById(id);
    }

    //查询多编辑员工
    @GetMapping("/getByIds")
    public Collection<Employee> getByIds(@RequestParam("id") List<Integer> id) {
        return employeeService.listByIds(id);
        //return employeeMapper.selectBatchIds(id);
    }

    //编辑员工
    @PutMapping("/update")
    public boolean update(@RequestBody Employee employee) {
        return employeeService.updateById(employee);
        //return employeeService.updateManual(employee);
    }

    //编辑多员工
    @PutMapping("/updates")
    public boolean updates(@RequestBody List<Employee> employeeList) {
        return employeeService.updateBatchById(employeeList);
    }

    //删除员工
    @DeleteMapping("/delete")
    public boolean delete(@RequestParam("id") Integer id) {
        return employeeService.removeById(id);

        //return employeeService.delete(id);
    }

    //删除多员工
    @DeleteMapping("/deletes")
    public boolean deletes(@RequestParam("id") List<Integer> id) {
        return employeeService.removeByIds(id);
    }

    //导出表数据
    @RequestMapping("/export")
    public void exportAll(HttpServletResponse response, @RequestParam("id") List<Integer> id) {
        List<Employee> employeeList = employeeService.list();//查询所有数据
        List<Employee> employeeList1 = (List<Employee>) employeeService.listByIds(id);//查询批量数据
        HSSFWorkbook wb = new HSSFWorkbook();//对应excel文件
        HSSFSheet sheet = wb.createSheet("基本资料");//对应一页
        HSSFRow row = sheet.createRow(0);//对应一行
        HSSFCell cell = row.createCell(0);//对应一列
        cell.setCellValue("编号");
        cell = row.createCell(1);//列号
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("工号");
        cell = row.createCell(3);
        cell.setCellValue("性别");
        cell = row.createCell(4);
        cell.setCellValue("出生日期");
        cell = row.createCell(5);
        cell.setCellValue("身份证号码");
        cell = row.createCell(6);
        cell.setCellValue("婚姻状况");
        cell = row.createCell(7);
        cell.setCellValue("民族");
        cell = row.createCell(8);
        cell.setCellValue("籍贯");
        cell = row.createCell(9);
        cell.setCellValue("政治面貌");
        cell = row.createCell(10);
        cell.setCellValue("电子邮件");
        cell = row.createCell(11);
        cell.setCellValue("电话号码");
        cell = row.createCell(12);
        cell.setCellValue("联系地址");
        cell = row.createCell(13);
        cell.setCellValue("部门");
        cell = row.createCell(14);
        cell.setCellValue("职业等级");
        cell = row.createCell(15);
        cell.setCellValue("职位");
        cell = row.createCell(16);
        cell.setCellValue("聘用形式");
        cell = row.createCell(17);
        cell.setCellValue("最高学历");
        cell = row.createCell(18);
        cell.setCellValue("专业");
        cell = row.createCell(19);
        cell.setCellValue("学校");
        cell = row.createCell(20);
        cell.setCellValue("入职日期");
        cell = row.createCell(21);
        cell.setCellValue("在职状态");
        cell = row.createCell(22);
        cell.setCellValue("合同期");
        cell = row.createCell(23);
        cell.setCellValue("转正日期");
        cell = row.createCell(24);
        cell.setCellValue("合同开始时间");
        cell = row.createCell(25);
        cell.setCellValue("合同到期时间");
        if (id.get(0) == 0) {
            idEstimate(employeeList, sheet);
        } else {
            idEstimate(employeeList1, sheet);
        }
        //生成excel文件并下载到客户端
        try {
            //设置响应头信息，仅.xls前名字能修改
            response.addHeader("Content-Disposition", "attachment;filename=employee.xls");
            //创建输出流
            OutputStream out = response.getOutputStream();
            wb.write(out);
            wb.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导出表数据，判断是否选中公用方法
    private void idEstimate(List<Employee> employeeList, HSSFSheet sheet) {
        Employee employee;
        HSSFRow row;
        HSSFCell cell;
        if (employeeList != null && employeeList.size() > 0) {
            for (int i = 0; i < employeeList.size(); i++) {
                employee = employeeList.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(employee.getId());
                cell = row.createCell(1);
                if (employee.getName() != null)
                    cell.setCellValue(employee.getName());
                else
                    cell.setCellValue("");
                cell = row.createCell(2);
                if (employee.getWorkID() != null)
                    cell.setCellValue(employee.getWorkID());
                else
                    cell.setCellValue("");
                cell = row.createCell(3);
                if (employee.getGender() != null)
                    cell.setCellValue(employee.getGender());
                else
                    cell.setCellValue("");
                cell = row.createCell(4);
                if (employee.getBirthday() != null)
                    cell.setCellValue(dateFormat.format(employee.getBirthday()));
                else
                    cell.setCellValue("");
                cell = row.createCell(5);
                if (employee.getIdCard() != null)
                    cell.setCellValue(employee.getIdCard());
                else
                    cell.setCellValue("");
                cell = row.createCell(6);
                if (employee.getWedlock() != null)
                    cell.setCellValue(employee.getWedlock());
                else
                    cell.setCellValue("");
                cell = row.createCell(7);
                if (employee.getNationId() != null)
                    cell.setCellValue(employee.getNationId());
                else
                    cell.setCellValue("");
                cell = row.createCell(8);
                if (employee.getNativePlace() != null)
                    cell.setCellValue(employee.getNativePlace());
                else
                    cell.setCellValue("");
                cell = row.createCell(9);
                if (employee.getPoliticId() != null)
                    cell.setCellValue(employee.getPoliticId());
                else
                    cell.setCellValue("");
                cell = row.createCell(10);
                if (employee.getEmail() != null)
                    cell.setCellValue(employee.getEmail());
                else
                    cell.setCellValue("");
                cell = row.createCell(11);
                if (employee.getPhone() != null)
                    cell.setCellValue(employee.getPhone());
                else
                    cell.setCellValue("");
                cell = row.createCell(12);
                if (employee.getAddress() != null)
                    cell.setCellValue(employee.getAddress());
                else
                    cell.setCellValue("");
                cell = row.createCell(13);
                if (employee.getDepartmentId() != null)
                    cell.setCellValue(employee.getDepartmentId());
                else
                    cell.setCellValue("");
                cell = row.createCell(14);
                if (employee.getJobLevelId() != null)
                    cell.setCellValue(employee.getJobLevelId());
                else
                    cell.setCellValue("");
                cell = row.createCell(15);
                if (employee.getPosId() != null)
                    cell.setCellValue(employee.getPosId());
                else
                    cell.setCellValue("");
                cell = row.createCell(16);
                if (employee.getEngageForm() != null)
                    cell.setCellValue(employee.getEngageForm());
                else
                    cell.setCellValue("");
                cell = row.createCell(17);
                if (employee.getTiptopDegree() != null)
                    cell.setCellValue(employee.getTiptopDegree());
                else
                    cell.setCellValue("");
                cell = row.createCell(18);
                if (employee.getSpecialty() != null)
                    cell.setCellValue(employee.getSpecialty());
                else
                    cell.setCellValue("");
                cell = row.createCell(19);
                if (employee.getSchool() != null)
                    cell.setCellValue(employee.getSchool());
                else
                    cell.setCellValue("");
                cell = row.createCell(20);
                if (employee.getBeginDate() != null)
                    cell.setCellValue(dateFormat.format(employee.getBeginDate()));
                else
                    cell.setCellValue("");
                cell = row.createCell(21);
                if (employee.getWorkState() != null)
                    cell.setCellValue(employee.getWorkState());
                else
                    cell.setCellValue("");
                cell = row.createCell(22);
                if (employee.getContractTerm() != null)
                    cell.setCellValue(employee.getContractTerm());
                else
                    cell.setCellValue("");
                cell = row.createCell(23);
                if (employee.getConversionTime() != null)
                    cell.setCellValue(dateFormat.format(employee.getConversionTime()));
                else
                    cell.setCellValue("");
                cell = row.createCell(24);
                if (employee.getBeginContract() != null)
                    cell.setCellValue(dateFormat.format(employee.getBeginContract()));
                else
                    cell.setCellValue("");
                cell = row.createCell(25);
                if (employee.getEndContract() != null)
                    cell.setCellValue(dateFormat.format(employee.getEndContract()));
                else
                    cell.setCellValue("");
            }
        }
    }

    //导入表数据
    @RequestMapping("/leadIn")
    public Boolean leadIn(MultipartFile file) {
        String fileName = file.getOriginalFilename();//获取上传的文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//获取上传文件的后缀
        fileName = UUID.randomUUID().toString() + suffixName;  //UUID和后缀名拼接，防止重名覆盖
        String filePath = null;//导入的文件放置位置
        try {
            filePath = ResourceUtils.getURL("classpath:files").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File fileDir = new File(filePath);//判断是否存在此目录
        if (!fileDir.exists()) {//不存在则创建
            fileDir.mkdir();
        }
        String path = filePath + File.separator + fileName;//File.separator表示路径的分隔符
        try {
            file.transferTo(new File(path));//将文件保存到path目录下，
        } catch (IOException e) {
            e.printStackTrace();
        }
        //根据excel文件生成HSSFWorkbook对象，封装了excel文件的所有信息
        InputStream is;
        HSSFWorkbook wb = null;
        try {
            is = new FileInputStream(path);
            wb = new HSSFWorkbook(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据wb获取HSSFSheet对象，封装了一页的所有信息
        HSSFSheet sheet = wb.getSheetAt(0);//页的下标，下标从0开始，依次增加
        HSSFRow row;
        HSSFCell cell;
        Employee employee;
        List<Employee> employeeList = new ArrayList<>();
        //根据sheet获取HSSFRow对象，封装了一行的所有信息
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {//sheet.getLastRowNum()获取最后一行的下标
            row = sheet.getRow(i);//行的下标，下标从1开始，依次增加
            employee = new Employee();
            //根据列获取HSSFCell对象，封装了一列的所有信息
            for (int j = 0; j < row.getLastCellNum(); j++) {//row.getLastCellNum()获取最后一列的下标+1
                cell = row.getCell(j);//列的下标，下标从0开始，依次增加
                //获取列中类型
                String cellValue = "";
                if (cell.getCellTypeEnum() == CellType.STRING) {//字符
                    cellValue = cell.getStringCellValue();
                } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {//数值
                    cellValue = cell.getNumericCellValue() + "";
                } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {//布尔
                    cellValue = cell.getBooleanCellValue() + "";
                } else if (cell.getCellTypeEnum() == CellType.FORMULA) {//公式
                    cellValue = cell.getCellFormula() + "";
                } else if (cell.getCellTypeEnum() == CellType.BLANK) {//空白
                    cellValue = "";
                }
                //获取列中的数据
                try {
                    if (j == 0) {
                        employee.setId(Integer.parseInt(cellValue));
                    } else if (j == 1) {
                        employee.setName(cellValue);
                    } else if (j == 2) {
                        employee.setWorkID(cellValue);
                    } else if (j == 3) {
                        employee.setGender(cellValue);
                    } else if (j == 4) {
                        employee.setBirthday(dateFormat.parse(cellValue));
                    } else if (j == 5) {
                        employee.setIdCard(cellValue);
                    } else if (j == 6) {
                        employee.setWedlock(cellValue);
                    } else if (j == 7) {
                        employee.setNationId(Integer.parseInt(cellValue));
                    } else if (j == 8) {
                        employee.setNativePlace(cellValue);
                    } else if (j == 9) {
                        employee.setPoliticId(Integer.parseInt(cellValue));
                    } else if (j == 10) {
                        employee.setEmail(cellValue);
                    } else if (j == 11) {
                        employee.setPhone(cellValue);
                    } else if (j == 12) {
                        employee.setAddress(cellValue);
                    } else if (j == 13) {
                        employee.setDepartmentId(Integer.parseInt(cellValue));
                    } else if (j == 14) {
                        employee.setJobLevelId(Integer.parseInt(cellValue));
                    } else if (j == 15) {
                        employee.setPosId(Integer.parseInt(cellValue));
                    } else if (j == 16) {
                        employee.setEngageForm(cellValue);
                    } else if (j == 17) {
                        employee.setTiptopDegree(cellValue);
                    } else if (j == 18) {
                        employee.setSpecialty(cellValue);
                    } else if (j == 19) {
                        employee.setSchool(cellValue);
                    } else if (j == 20) {
                        employee.setBeginDate(dateFormat.parse(cellValue));
                    } else if (j == 21) {
                        employee.setWorkState(cellValue);
                    } else if (j == 22) {
                        employee.setContractTerm(Double.parseDouble(cellValue));
                    } else if (j == 23) {
                        employee.setConversionTime(dateFormat.parse(cellValue));
                    } else if (j == 24) {
                        employee.setBeginContract(dateFormat.parse(cellValue));
                    } else if (j == 25) {
                        employee.setEndContract(dateFormat.parse(cellValue));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            employeeList.add(employee);//每一行对象保存到list中
        }
        return employeeService.saveBatch(employeeList);//将所有数据保存到数据库中返回判断
    }
}
